//
//  ViewController.m
//  猜字游戏
//
//  Created by Jorn.Wu on 15/7/16.
//  Copyright (c) 2015年 Jorn.Wu. All rights reserved.
//

#import "ViewController.h"
#import "QuestionModel.h"


#define JWLabelWidth 40
#define JWLabelHeight 40
#define JWBtnWidth 40
#define JWBtnHeight 40


@interface ViewController ()
- (IBAction)tipBtn:(id)sender;
- (IBAction)helpBtn:(id)sender;//未写
- (IBAction)scalBtn:(id)sender;
- (IBAction)nextBtn:(id)sender;
- (IBAction)redoBtn:(id)sender;
- (IBAction)pauseBtn:(id)sender;
- (IBAction)startBtn:(id)sender;
- (IBAction)coinBtn:(UIButton *)sender;//未写
@property (weak, nonatomic) IBOutlet UIButton *coinNum;
@property (weak, nonatomic) IBOutlet UIScrollView *mScrollView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *numTitle;
@property (weak, nonatomic) IBOutlet UILabel *imgTitle;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *finishTip;
@property (weak, nonatomic) IBOutlet UIButton *coinBtn;
@property (weak, nonatomic) IBOutlet UIView *centerView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIButton *startBtn;
@property (weak, nonatomic) IBOutlet UIButton *pauseBtn;

@property (nonatomic, strong) QuestionModel *question;
@property (nonatomic, strong) NSMutableArray *questionlist;
@property (nonatomic, strong) NSMutableArray *centerLabelAr;
@property (nonatomic, strong) NSTimer *mTimer;
@property (nonatomic, assign) int index;//第几题
@property (nonatomic, assign) int counting;
@property (nonatomic, assign) int total;
@property (nonatomic, assign) BOOL isLarge;
@property (nonatomic, assign) int time;//计时，当前时钟
@property (nonatomic, assign) BOOL isFinish;
@property (nonatomic, assign) int mMoney;//现在的金币
@property (nonatomic, assign) int preTime;//上一题完成时的时钟；
@property (nonatomic, assign) int preMoney;//之前的金币

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _preTime = 0;
    _time = 0;
    _index = 0;
    _preMoney = 0;
    _mMoney = 0;
    _isLarge = NO;
    _isFinish = NO;
    
    [self.coinBtn setTitle:[NSString stringWithFormat:@"%d",_mMoney] forState:UIControlStateNormal];
    
    self.finishTip.font = [UIFont systemFontOfSize:13];
    self.finishTip.text = @"点击start按钮开始答题";
    
    self.timeLabel.text = @"0秒";
    
}
#pragma mark - 开始
- (IBAction)startBtn:(id)sender {
    _mTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    _finishTip.hidden = YES;
    
    [self loading];
    
    _pauseBtn.enabled = YES;
    _startBtn.enabled = NO;
}
- (void)timerAction{
    _time++;
    _timeLabel.text = [NSString stringWithFormat:@"%d秒",_time];
}
#pragma mark - 加载数据
- (void)loading{
    [self loadCenterViewWithNumber:_index];
    [self loadBottomViewWithNumber:_index];
    [self loadImageViewWithNumber:_index];
    [self loadTitleWithNumber:_index];
}
#pragma mark - 给questionlist赋值
- (NSMutableArray *)questionlist{
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"questions" ofType:@"plist"];
    NSArray *array = [NSArray arrayWithContentsOfFile:path];
    
    if (_questionlist == nil) {
        
        NSMutableArray *tempAr = [NSMutableArray array];
        for (int i = 0; i < array.count; i++) {
            NSDictionary *dic = array[i];
            QuestionModel *question = [QuestionModel questionModelWithDictionary:dic];
            
            [tempAr addObject:question];
        }
        _questionlist = tempAr;
    }
    
    return _questionlist;
}
#pragma mark - 图片加载方法
- (void)loadImageViewWithNumber:(int)index{
    QuestionModel *question = self.questionlist[index];
    NSString *imgName = question.icon;
    self.imageView.image = [UIImage imageNamed:imgName];
}
- (void)loadTitleWithNumber:(int)index{
    QuestionModel *question = self.questionlist[index];
    NSString *title = question.title;
    self.imgTitle.text = title;
    NSString *numTitle = [NSString stringWithFormat:@"%d/%d",index + 1,(int)self.questionlist.count];
    self.numTitle.text = numTitle;
}
#pragma mark - centerLabelAr的get方法
- (NSMutableArray *)centerLabelAr{
    if (_centerLabelAr == nil) {
        _centerLabelAr = [NSMutableArray array];
    }
    return _centerLabelAr;
}
#pragma mark - 中间view的加载
- (void)loadCenterViewWithNumber:(int)index{
    QuestionModel *question = self.questionlist[index];
    
    int num = (int)[question.answer length];
    _total = num;
    _counting = 0;
    
    CGFloat pading = 10;
    CGFloat startX = (_centerView.frame.size.width - JWLabelWidth * num - pading * (num - 1)) * 0.5;
    
    
    for (int i = 0; i < num; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(startX + (JWLabelWidth + pading) * i, (_centerView.frame.size.height - JWLabelHeight) * 0.5, JWLabelWidth, JWLabelHeight)];
        label.backgroundColor = [UIColor whiteColor];
        label.font = [UIFont systemFontOfSize:20];
        label.textAlignment = NSTextAlignmentCenter;
        label.tag = i;
        
        [_centerView addSubview:label];
        
        [self.centerLabelAr addObject:label];
    }
}
#pragma mark - 底部视图的加载
- (void)loadBottomViewWithNumber:(int)index{
    QuestionModel *question = _questionlist[index];
//
    NSArray *array = question.options;
    
    int num = (int)array.count;
    int col = 7;
    CGFloat pading = (_bottomView.frame.size.width - JWBtnWidth * col) / (col + 1);
    
    for (int i = 0; i < num; i++) {
        CGFloat C = i % col;
        CGFloat R = i / col;
        
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(pading + (pading + JWBtnWidth) * C,10 + pading + (pading + JWBtnHeight) * R, JWBtnWidth, JWBtnHeight)];
        btn.backgroundColor = [UIColor whiteColor];
        btn.tag = i;
        NSString *str = array[i];
        [btn setTitle:str forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:20];
        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];

        [btn addTarget:self action:@selector(bottomBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.bottomView addSubview:btn];
    }
    
}
#pragma mark - 底部视图上的按钮的响应方法
- (void)bottomBtnAction:(UIButton *)btn{
    if (_counting < _centerLabelAr.count) {
        UILabel *label = _centerLabelAr[_counting];
        label.text = btn.titleLabel.text;
//        btn.enabled = NO;
        btn.hidden = YES;
        
        if (_counting == (_centerLabelAr.count - 1)) {//最后一个
            [self isRight];
        }
        
    }
    
    if (_counting < _centerLabelAr.count) {//停止增加，counting即为要填空格的数量
        _counting++;
    }
    
}
#pragma mark - 判断答案是否正确
- (void)isRight{
    QuestionModel *question = self.questionlist[_index];
    NSString *answer = question.answer;
    NSMutableString *myAnswer = [NSMutableString string];
    for (int i = 0; i < _centerLabelAr.count; i++) {
        UILabel *label = _centerLabelAr[i];
        [myAnswer appendString:label.text];
    }
    if ([myAnswer isEqualToString:answer]) {
        
       int num = (int)(1.0/ (_time - _preTime) * 10000); //金钱的计算公式
        _mMoney =_preMoney + num;
        
        [_coinBtn setTitle:[NSString stringWithFormat:@"%d",_mMoney] forState:UIControlStateNormal];
        
        _preMoney = _mMoney;
        _preTime = _time;
        
        NSLog(@"%d",num);
        
        NSLog(@"正确");
        _isFinish = YES;
        _finishTip.hidden = NO;
        _finishTip.text = @"回答正确，点击下一题继续！";
    }else {
        NSLog(@"错误");
        _finishTip.hidden = NO;
        _finishTip.text = @"回答错误哦！";
    }
    
}
#pragma mark - 提示按钮的响应方法
- (IBAction)tipBtn:(id)sender {
    if (_counting == 0) {
        
//       1、自动填充第一个字符，当没有手动填充前才有效
        
        QuestionModel *question = self.questionlist[_index];
        NSString *answer = question.answer;
        NSString *firstWord = [answer substringToIndex:1];//获取答案的第一个字符，自动填充
        
        UILabel *label = _centerLabelAr[_counting];
        label.text = firstWord;
        if (_total == 1) {
            [self isRight];
        }
        
        _total = _total - 1;
        _counting = _counting + 1;
        
//        将含有该字符的按钮隐藏
        
        int index = (int)[question.options indexOfObject:firstWord];
        UIButton *btn = (UIButton *)[self.bottomView viewWithTag:index];
        btn.hidden = YES;
        
    }
}
//---------------------------------------------------

- (IBAction)helpBtn:(id)sender {
    
    //  寻求帮助（进入网页）
 
}

//---------------------------------------------------
#pragma mark - 缩放按钮的响应方法
- (IBAction)scalBtn:(id)sender {
    _isLarge = !_isLarge;
    if (_isLarge) {
        self.mScrollView.layer.anchorPoint = CGPointMake(0.63, 0.6);
        self.mScrollView.layer.transform = CATransform3DMakeScale(1.5, 1.5, 0);
    }else {
        self.mScrollView.layer.anchorPoint = CGPointMake(0.5, 0.5);
        self.mScrollView.layer.transform = CATransform3DMakeScale(1, 1, 0);
    }
    
}
#pragma mark - 下一题按钮的响应方法
- (IBAction)nextBtn:(id)sender {
    if (_isFinish) {//完成上一题才能进入下一题
        [self refreshData];
        _index++;
        
        if (_index < self.questionlist.count) {
            [self loading];
        }else {
            [self.mTimer invalidate];
            
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake((self.bottomView.frame.size.width - 300) * 0.5, (self.bottomView.frame.size.height - 50) * 0.5, 300, 50)];
            label.numberOfLines = 0;
            label.text = [NSString stringWithFormat:@"恭喜你通关了！用时%d秒！共获金币%d元",_time,_mMoney];
            [self.bottomView addSubview:label];
        }
        
        _isFinish = NO;
        _finishTip.hidden = YES;
    }else {
        _finishTip.hidden = NO;
        _finishTip.text = @"先完成本题才能继续哦！";
    }
}
#pragma mark - 返回按钮的响应方法
- (IBAction)redoBtn:(id)sender {
    if (_counting >= 0) {
        _counting = _counting - 1;//因为填字后已经移动到下一个了
        _total = _total + 1;
        
        if (_counting < 0 ) {
            _counting = 0;
        }
        
        QuestionModel *question = self.questionlist[_index];
        //       1、去掉最后一个字，当有字符才有效
        
//        UILabel *label = (UILabel *)[self.centerView viewWithTag:_counting];
        UILabel *label = _centerLabelAr[_counting];
        
        NSString *lastWord = label.text;
        
        label.text = nil;
        
        //       2、将含有该字符的按钮显示
        
        int index = (int)[question.options indexOfObject:lastWord];
        UIButton *btn = (UIButton *)[self.bottomView viewWithTag:index];
        btn.hidden = NO;
        
        }
    
}
#pragma mark - 暂停按钮的响应方法
- (IBAction)pauseBtn:(UIButton *)sender {
    [self.mTimer invalidate];
    [self refreshData];
    _pauseBtn.enabled = NO;
    _startBtn.enabled = YES;
    self.imageView.image = [UIImage imageNamed:@"Icon-120"];

}

//----------------------------------------------------

- (IBAction)coinBtn:(UIButton *)sender {
    
    //     查看金币
    
}

//----------------------------------------------------
#pragma mark - 刷新数据
- (void)refreshData{
//      刷新数据
    
    for (UIView *obj in self.centerView.subviews) {
        [obj removeFromSuperview];
    }
    for (UIView *obj in self.bottomView.subviews) {
        [obj removeFromSuperview];
    }
    _total = 0;
    _counting = 0;
    _centerLabelAr = nil;
    
    if (_isLarge) {//如果图片还没缩小，自动缩小
        [self scalBtn:nil];
    }
}
@end

